package com.atguigu.tingshu.user.strategy.impl;

import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.model.user.UserVipService;
import com.atguigu.tingshu.model.user.VipServiceConfig;
import com.atguigu.tingshu.user.mapper.UserInfoMapper;
import com.atguigu.tingshu.user.mapper.UserVipServiceMapper;
import com.atguigu.tingshu.user.mapper.VipServiceConfigMapper;
import com.atguigu.tingshu.user.strategy.ItemTypeStrategy;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import org.joda.time.LocalDateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service("1003")
public class savePaidRecord implements ItemTypeStrategy {
    @Autowired
    private VipServiceConfigMapper vipServiceConfigMapper;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private UserVipServiceMapper userVipServiceMapper;
    @Override
    public void savePaidRecord(UserPaidRecordVo userPaidRecordVo) {


        //  vip:user_vip_service 用户VIP服务记录表： userInfo.setIsVip(1);
        //先获取到用户购买vip的哪种套餐 1,3,12 月；
        List<Long> itemIdList = userPaidRecordVo.getItemIdList();
        //远程调用vipServiceConfigMapper,根据套餐id获取套餐信息 vipServiceConfig
        VipServiceConfig vipServiceConfig = vipServiceConfigMapper.selectById(itemIdList.get(0));
        //  获取购买的月数
        Integer serviceMonth = vipServiceConfig.getServiceMonth();
        //定义当前系统时间 作为用户vip开始时间计算 currentTime 默认非续期 vip开始日期为当前日期
        Date currentTime = new Date();
        //  分情况：是否属于续期情况（当前这个用户属于vip也没有过期）
        //调用本模块userInfoMapper，查询用户信息
        UserInfo userInfo = userInfoMapper.selectById(userPaidRecordVo.getUserId());
        // 判断用户信息是否是vip、vip是否过期，判断是否是续期：
        if (1 == userInfo.getIsVip().intValue() && userInfo.getVipExpireTime().after(new Date())) {
            //续期，当前系统时间 即用户vip开始时间计算 为用户VIP结束时间vip_expire_time
            currentTime=userInfo.getVipExpireTime();
        }
        //计算vip结束日期expireTime  LocalDate LocalDateTime LocalTime-->LocalDateTime().plusMonths().toDate
        Date expireTime = new LocalDateTime(currentTime).plusMonths(serviceMonth).toDate();
        //  创建UserVipService对象 保存vip:user_vip_service 用户VIP服务记录表：
        UserVipService userVipService = new UserVipService();
        userVipService.setOrderNo(userPaidRecordVo.getOrderNo());
        userVipService.setUserId(userPaidRecordVo.getUserId());
        userVipService.setStartTime(currentTime);
        userVipService.setExpireTime(expireTime);
        userVipServiceMapper.insert(userVipService);

//            //排除异常 测试Seata 分布式事务
//            int i=1/0;

        //修改远程调用返回的userinfo信息 IsVip(1); VipExpireTime(expireTime);
        userInfo.setIsVip(1);
        userInfo.setVipExpireTime(expireTime);
        userInfoMapper.updateById(userInfo);
    }
}
